import BannerPng from "@/assets/images/banner.png";
import SearchPng from "@/assets/images/search.png";
import { useEffect, useRef, useState } from "react";
import * as echarts from "echarts";
import { post } from "@/request/index";
import { useNavigate } from "react-router";
import { Select } from "antd";

export default function Home() {
  const barChartRef = useRef<HTMLDivElement>(null);
  const pieChartRef1 = useRef<HTMLDivElement>(null);
  const pieChartRef2 = useRef<HTMLDivElement>(null);
  let chart: any;
  let chart1: any;
  let chart2: any;
  const [typeList, setTypeList] = useState<any[]>([]);
  const navigate = useNavigate();
  const [keyword, setKeyword] = useState("");
  const baseURL = import.meta.env.VITE_BASE_URL;
  const [options, setOptions] = useState<any>([]);
  const [value, setValue] = useState("");

  const initEcharts = (values: any[]) => {
    chart = echarts.init(barChartRef.current);
    chart.setOption({
      xAxis: {
        type: "category",
        data: values.map((item) => item.speciesName),
        axisLabel: {
          interval: 0,
          rotate: 20,
        },
      },
      grid: {
        right: 0,
        left: "10%",
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          data: values.map((item) => item.allNumber),
          type: "bar",
          label: {
            show: true,
            position: "top",
          },
          itemStyle: {
            // 使用方法一的写法
            color: new echarts.graphic.LinearGradient(0, 1, 1, 0, [
              { offset: 0, color: "#f3b255" },
              { offset: 1, color: "#eb7833" },
            ]),
          },
        },
      ],
    });
  };

  const initPieChart1 = (data: any[]) => {
    chart1 = echarts.init(pieChartRef1.current);
    chart1.setOption({
      tooltip: {
        trigger: "item",
      },
      series: [
        {
          name: "Statistics of data different lengths of repetitive units",
          type: "pie",
          radius: "80%",
          data: data.map((item: any) => ({ value: item.dataSubsetCount, name: item.dataSubset })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
        {
          name: "Statistics of data different lengths of repetitive units",
          type: "pie",
          radius: "80%",
          data: data.map((item: any) => ({ value: item.dataSubsetCount, name: item.dataSubset })),
          label: {
            normal: {
              show: true,
              position: "inner", // 数值显示在内部
              formatter: "{c}", // 格式化数值百分比输出
            },
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    });
  };
  const initPieChart2 = (data: any) => {
    chart2 = echarts.init(pieChartRef2.current);
    chart2.setOption({
      tooltip: {
        trigger: "item",
      },
      series: [
        {
          name: "Statistics of STRs data subsets",
          type: "pie",
          radius: "80%",
          data: data.map((item: any) => ({ value: item.totalCount, name: item.repeatCategory })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
        {
          name: "Statistics of STRs data subsets",
          type: "pie",
          radius: "80%",
          data: data.map((item: any) => ({ value: item.totalCount, name: item.repeatCategory })),
          label: {
            normal: {
              show: true,
              position: "inner", // 数值显示在内部
              formatter: "{c}", // 格式化数值百分比输出
            },
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    });
  };

  const resizeEcharts = () => {
    chart && chart.resize();
    chart1 && chart1.resize();
    chart2 && chart2.resize();
  };

  const initAddEventListeren = () => {
    window.addEventListener("resize", resizeEcharts);
  };

  const getAllTypeList = () => {
    post("/function/getAllType", { params: {} }).then((res: any) => {
      setTypeList([...res.vos]);
      initEcharts([...res.vos]);
    });
  };

  const getPieChartData = () => {
    post("/function/getMutationDataList").then((res: any[]) => {
      initPieChart1(res || []);
    });
    post("/function/getFourDataList").then((res: any[]) => {
      initPieChart2(res || []);
    });
  };

  const gotoSearchPage = (item: any) => {
    navigate(`/search?isSpecies=${1}&id=${item.id}`);
  };

  const searchInput = () => {
    navigate(`/search?name=${keyword}&value=${value}`);
  };

  const handleChange = (value: string) => {
    setValue(value);
    if (value == "1") {
      setKeyword("CAG");
    }
    if (value == "2") {
      setKeyword("NA only");
    }
    if (value == "3") {
      setKeyword("GGGGCC");
    }
    if (value == "4") {
      setKeyword("2MS5");
    }
    if (value == "5") {
      setKeyword("NMR;X-ray");
    }
    if (value == "6") {
      setKeyword("2614806");
    }
    if (value == "12") {
      setKeyword("CUGBP1 RRM1/2");
    }
    if (value == "7") {
      setKeyword("NMR");
    }
  };

  const getOptions = () => {
    post("/function/getRibozymeSearchType").then((res: any) => {
      setValue(res[0].id);
      setKeyword("CAG");
      setOptions([...res].map((item) => ({ value: item.id, label: item.fieldName })));
    });
  };

  useEffect(() => {
    initAddEventListeren();
    getAllTypeList();
    getPieChartData();
    getOptions();
    return () => {
      window.removeEventListener("resize", resizeEcharts);
    };
  }, []);
  return (
    <div>
      <div
        style={{
          position: "relative",
          maxWidth: "1200px",
          margin: "0 auto",
        }}
        className="homeBox"
      >
        <div
          style={{
            fontSize: "50px",
            textAlign: "center",
            background: "#5ea1f7",
            color: "#fff",
            margin: "20px 0",
            padding: "10px 0",
          }}
        >
          <div> STRDB</div>
          <div style={{ fontSize: "16px" }}>Short Tandem Repeats Database</div>
        </div>
        <div style={{ background: "#fff", textAlign: "left", padding: "20px" }}>
          The STRDB collects 3D structures of short tandem repeats (STRs) found in Protein Data Bank. It includes 3D
          structures of nucleic acid, nucleic acid-ligand complex, and nucleic acid-protein complex. In addition, it
          also includes 3D structures of STRs investigated by molecular dynamics simulations. STRDB stores DNA or RNA
          sequence, ligand name, protein name, 3D structural determination method (NMR, X-ray crystallography, cryo-EM),
          experimental conditions (temperature, pH, and ions), PDB ID, and graphical 3D structure views.
        </div>

        <div style={{ background: "#fff", margin: "20px 0", padding: "20px" }}>
          <div style={{ fontSize: "20px", fontWeight: "700", textAlign: "center", fontStyle: "italic" }}>
            Click any button to view category data
          </div>
          <div
            style={{
              marginTop: "40px",
              display: "flex",
              gap: "20px",
              justifyContent: "space-evenly",
              textAlign: "center",
            }}
            className="species"
          >
            {typeList.map((item, index) => {
              return (
                <div key={index} style={{ cursor: "pointer" }} onClick={() => gotoSearchPage(item)}>
                  <div key={item.id} style={{ position: "relative", width: "100%" }}>
                    <img
                      src={baseURL + item.speciesImage}
                      alt=""
                      style={{ width: "200px", height: "300px", objectFit: "contain" }}
                      className="navImag"
                    />
                  </div>
                  <div
                    style={{
                      fontWeight: "700",
                      whiteSpace: "nowrap",
                      textAlign: "center",
                    }}
                  >
                    {item.speciesName}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ background: "#fff", textAlign: "center", padding: "20px" }}>
          <div style={{ fontSize: "20px", fontWeight: "700" }}>Quick database search</div>
          <div
            className="search1"
            style={{
              display: "flex",
              alignItems: "center",
              maxWidth: "1000px",
              marginTop: "20px",
              justifyContent: "center",
              margin: "20px auto 0 auto",
            }}
          >
            <div
              style={{
                flex: "1",
                borderRadius: "40px",
                border: "1px solid #5ea1f7",
                padding: "15px",
                display: "flex",
                alignItems: "center",
                gap: "20px",
                height: "50px",
                boxSizing: "border-box",
              }}
            >
              <div style={{ borderRight: "1px solid #000", paddingRight: "20px" }}>
                <Select
                  value={value}
                  style={{ width: "20vw", maxWidth: "200px" }}
                  options={options}
                  onChange={handleChange}
                />
              </div>
              <div style={{ flex: "1" }}>
                <input
                  value={keyword || ""}
                  style={{ width: "100%", height: "30px", border: "none", outline: "none" }}
                  type="text"
                  placeholder="Enter any string of …"
                  onChange={(e) => setKeyword(e.target.value)}
                />
              </div>
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                background: "linear-gradient(90deg, #0078f9, #56b8fb)",
                padding: "0 20px",
                gap: "5px",
                color: "#fff",
                borderRadius: "30px",
                marginLeft: "-60px",
                cursor: "pointer",
                height: "50px",
              }}
              onClick={searchInput}
            >
              <img src={SearchPng} alt="" />
              <div className="searchText">Search</div>
            </div>
          </div>
        </div>
        <div style={{ background: "#fff", padding: "20px", marginTop: "20px" }} className="number">
          <div style={{ display: "flex", alignItems: "center" }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: "18px", marginBottom: "10px", textAlign: "center" }}>
                Statistics of data different lengths of repetitive units
              </div>
              <div style={{ width: "100%", height: "400px" }} ref={pieChartRef1}></div>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: "18px", marginBottom: "10px", textAlign: "center" }}>
                Statistics of STRs data subsets
              </div>
              <div style={{ width: "100%", height: "400px" }} ref={pieChartRef2}></div>
            </div>
          </div>
        </div>
        <div style={{ background: "#fff", marginTop: "20px", padding: "20px" }}>
          <div style={{ fontSize: "20px", fontWeight: "700" }}>Update log</div>
          <div className="update" style={{ marginTop: "40px" }}>
            <div style={{ fontWeight: 700, fontSize: "18px", marginBottom: "10px" }}>
              Recent update: {new Date().toLocaleDateString()}
            </div>
            <div style={{ flex: "2", height: "600px" }}>
              <div style={{ width: "100%", height: "600px" }} ref={barChartRef}></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
